<?php
namespace Weixin\Controller;
use Think\Controller;
use Alidayu\AlidayuClient as Client;
use Alidayu\Request\SmsNumSend;
class WeixinDevelopmentController extends WeixinCommonController
{
    function phone_verification(){
		    //dump(I('get.'));
			$this->display();
    }
    function weixinVerification(){
        //https://open.weixin.qq.com/connect/oauth2/authorize?appid=wx9e81b4c3c459a480&redirect_uri=http://www.bangpt.com/bn_test/index.php/Weixin/WeixinDevelopment/phone_verification?&response_type=code&scope=snsapi_base&state=1#wechat_redirect
      if (I('validate_code') == session('code')) {
			$appid = C('WEIXIN_APPID');
			$secret = C('WEIXIN_APPSECRET');
			$code = $_GET["code"];
	
		    $ret = file_get_contents("access_token.json");
			$token = json_decode($ret, true);
	
			$oauth2Url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=$appid&secret=$secret&code=$code&grant_type=authorization_code";
			$oauth2 = $this->getJson($oauth2Url);
			
            $ret = M('dispatch')->where(array('mobile'=>I('phone')))->field('weinxin_openid,dispatch_id')->find();

			if($ret){
               if(NULL === $ret['weinxin_openid']){
					$retss = M('dispatch')->where(array('dispatch_id'=>$ret['dispatch_id']))->save(array('weinxin_openid'=>$oauth2['openid']));
						//dump($oauth2['openid']);
					if($retss){
							$this->pk_success("恭喜您，绑定成功，您可以在APP端提现了");
						}else{
							$this->pk_error("抱歉，绑定失败，请重试!");
						}
					}else{
						$this->pk_error("本次绑定失败，您已经绑定过微信，可以直接在app中提现了");
					}
				
            }else{
				$this->pk_error("抱歉，无此跑客!");
			}
        }else{
			$this->pk_error("抱歉，短信验证码验证失败!");
		}
    }

//https://open.weixin.qq.com/connect/oauth2/authorize?appid=wx9e81b4c3c459a480&redirect_uri=http://www.bangpt.com/bn_test/index.php/Weixin/WeixinDevelopment/phone_verification?&response_type=code&scope=snsapi_base&state=1#wechat_redirect
    /**
     * @api {get} getSMS/phone/:phone 获取短信验证码
     * @apiName 获取短信验证码
     * @apiGroup pt
     *
     * @apiParam {Int} phone 获取短信验证码的手机号.
     **/
    function getSMS()
    {
        //$V1 = new V1Controller();
       $ret = M('dispatch')->where(array('mobile'=>I('phone')))->find();
        if($ret){
            if ($this->sendMSM(I('phone'))) {
                return RET_NO_V(200, "短信发送成功！");
            } else {
                return RET_NO_V(400, "短信发送失败！");
            }
        }else{
            return RET_NO_V(400, "您输入的用户不存在！");
        }
    }
    //发送注册验证码
    protected function sendMSM($tel)
    {
        $client = new Client;
        $request = new SmsNumSend;
        //session("code", null);
        $code = $this->randString();
        // 短信内容参数
        $smsParams = array(
            'code' => $code,
            'product' => '帮你跑腿'
        );

        // 设置请求参数
        $req = $request->setSmsTemplateCode('SMS_24040005')
            ->setRecNum($tel)
            ->setSmsParam(json_encode($smsParams))
            ->setSmsFreeSignName('帮你跑腿')
            ->setSmsType('normal')
            ->setExtend('demo');

        $status = $client->execute($req);
        if ($status["alibaba_aliqin_fc_sms_num_send_response"]["result"]["success"]) {
            //session("code", $code);
			$_SESSION['code'] = $code;
            return true;
        } else {
            return false;
        }

    }
    protected static function randString($len = 4)
    {
        $chars = str_repeat('0123456789', $len);
        $chars = str_shuffle($chars);
        $str = substr($chars, 0, $len);
        return $str;
    }
    function checkWeixin(){
        //微信会发送4个参数到我们的服务器后台 签名 时间戳 随机字符串 随机数

        $signature = $_GET["signature"];
        $timestamp = $_GET["timestamp"];
        $nonce = $_GET["nonce"];
        $echostr = $_GET["echostr"];
        $token = "bnpt";

        // 1）将token、timestamp、nonce三个参数进行字典序排序
        $tmpArr = array($nonce,$token,$timestamp);
        sort($tmpArr,SORT_STRING);

        // 2）将三个参数字符串拼接成一个字符串进行sha1加密
        $str = implode($tmpArr);
        $sign = sha1($str);

        // 3）开发者获得加密后的字符串可与signature对比，标识该请求来源于微信
        if ($sign == $signature) {
            echo $echostr;
        }
    }
	
	   //请求接口获取json数据
    protected static function getJson($url)
    {
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        $output = curl_exec($ch);
        curl_close($ch);
        return json_decode($output, true);
    }
	
	public function pk_success($msg){
		$this->assign('msg',$msg);
		$this->display('pk_success');
	}
	
	public function pk_error($msg){
		$this->assign('msg',$msg);
		$this->display('pk_error');
	}
public function get_code()
{
if (isset($_GET['code'])){
    echo $_GET['code'];
}else{
    echo "NO CODE";
}
}


}